package com.frameDemo.utils;

import com.frameDemo.frame.FrameHead;
import com.frameDemo.frame.Frame;
import com.frameDemo.frame.FrameData;

/**
 * Created by TianyuanPan on 10/16/16.
 */
public class FrameCheckSum {

    public static byte getFrameHeadCheckSum(FrameHead head) {

        byte checkSum;
        byte[] res = head.getRes();
        byte[] len = head.getLen();

        checkSum = (byte) (FrameHead.startFlagA + FrameHead.startFlagB +
                head.getVersion() + head.getId() + res[0] + res[1] + res[2] +
                res[3] + len[0] + len[1] + head.getdChk());

        return (byte) (~checkSum + 1);
    }


    public static boolean isFrameHeadCheckSumOK(FrameHead head) {

        int checkSum;
        byte[] res = head.getRes();
        byte[] len = head.getLen();

        checkSum = FrameHead.startFlagA + FrameHead.startFlagB +
                head.getVersion() + head.getId() + res[0] + res[1] + res[2] +
                res[3] + len[0] + len[1] + head.getdChk() + head.gethChk();


        return (checkSum == 0);
    }


    public static byte getFrameDataCheckSum(FrameData data) {

        byte checkSum = 0;
        for (byte b : data.getData())
            checkSum = (byte) (checkSum + b);

        return (byte) ((~checkSum) + 1);
    }


    public static boolean isFrameDataCheckSumOK(Frame frame) {

        return (frame.getHead().getdChk() == frame.getData().getCheckSum());
    }

}
